package com.beem.project.beem.ui.views;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.beem.project.beem.R;
import com.beem.project.beem.R.drawable;
import com.beem.project.beem.service.Contact;
import com.beem.project.beem.ui.Chat;
import com.beem.project.beem.ui.Chat.ExpressionItemAdapter;
import com.butterfly.vv.Constants;
import com.butterfly.vv.db.City;
import com.butterfly.vv.db.Colleage;
import com.butterfly.vv.db.DBService;
import com.butterfly.vv.db.Provice;
import com.butterfly.vv.vv.utils.Debug;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.text.Editable;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
 
public class InputFieldPopupWindow extends PopupWindow {
 
 
    private Button btn_take_photo, btn_pick_photo, btn_cancel,btn_defaut;
    TextView parameters_tx;
    private View mMenuView;
//    AutoCompleteTextView serverEdit;
    Activity mcontext;
    private Spinner prov_spr;
    private Spinner uni_spr;
   	private Spinner city_spr;
   	LinearLayout dialog_layout_content;
   	public String selectedPro,selectedCity,selectedUniName;
    List<Provice> provices;
    List<Colleage>colleages;
    DBService dbService;
    List<City> cities ;
    private String[] arrayOfString1 ;
    ArrayAdapter<String> adapter02;
    ArrayAdapter pro_adapter;
    ArrayAdapter uni_adapter;
    String selectedCityCode;
    LinearLayout layout_pro_city,layout_provice,layout_city,layout_university;
    
    Button editbutton;
	GridView message_facebar_gv_emotes;
	LinearLayout message_layout_container_emotes;
	 private EditText mInputField;
	    private Button mSendButton;
	    InputMethodManager imm;
 
    public InputFieldPopupWindow(Activity context,OnClickListener itemsOnClick) {
        super(context);
        mcontext = context;
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        //mMenuView = inflater.inflate(R.layout.input_field_popup_win, null);
        mMenuView = inflater.inflate(R.layout.params_for_comment_in_listview, null);
        context.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
//        EditText message_ed_msgeditor = (EditText) mMenuView.findViewById(R.id.message_ed_msgeditor);
//        message_ed_msgeditor.setFocusable(true);
//        bySex(itemsOnClick);
        initview(mMenuView,itemsOnClick);
        setParams();
 
    }
    
    private void initview(View viewc,OnClickListener itemsOnClick) {
    	message_layout_container_emotes = (LinearLayout) viewc.findViewById(R.id.message_layout_container_emotes);
    	message_facebar_gv_emotes = (GridView) viewc.findViewById(R.id.message_facebar_gv_emotes);
    	loadExpression(Chat.PATTERN);
    	//ArrayList<HashMap<String, Object>> datas = initEmoteDatas();
    	//message_facebar_gv_emotes.setAdapter(new SimpleAdapter(this, datas, R.layout.message_emote_item, new String[] {"image"},  new int[]{R.id.emote_imageview}));
    	message_facebar_gv_emotes.setAdapter(new ExpressionItemAdapter(viewc.getContext()));
    	message_facebar_gv_emotes.setOnItemClickListener(new OnItemClickListener() {

    		@Override
    		public void onItemClick(AdapterView<?> adpater, View arg1, int location,
    				long arg3) {
    			// TODO Auto-generated method stub
    			choseEmoteTosend(adpater, location);
    		}
    	});
    	
    	//mInputField = (EditText) findViewById(R.id.chat_input);//20130322
    	mInputField = (EditText)  viewc.findViewById(R.id.message_ed_msgeditor);
    	mInputField.setInputType(INPUT_METHOD_NEEDED);
    	//mInputField.setOnEditorActionListener(this);
    	mInputField.requestFocus();
    	// 获取编辑框焦点
    	mInputField.setFocusable(true);
    	//打开软键盘
    	 imm = (InputMethodManager) mcontext
    	  .getSystemService(Context.INPUT_METHOD_SERVICE);
    	imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    	
    	
    	ImageButton message_btn_openemotes = (ImageButton)  viewc.findViewById(R.id.message_btn_openemotes);
    	message_btn_openemotes.setOnClickListener(new OnClickListener() {
    		
    		@Override
    		public void onClick(View v) {
    			// TODO Auto-generated method stub
    			if (message_layout_container_emotes.getVisibility() == View.GONE) {
    				imm.hideSoftInputFromWindow(mInputField.getWindowToken(), 0);
    				
    				message_layout_container_emotes.setVisibility(View.VISIBLE);
    			} else {
    				message_layout_container_emotes.setVisibility(View.GONE);
    				imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    			}
    		}
    	});
    	
    	
    	
    	//mSendButton = (Button) findViewById(R.id.chat_send_message);//20130322
    	mSendButton = (Button)  viewc.findViewById(R.id.message_btn_sendtext);
    	mSendButton.setOnClickListener(itemsOnClick);
//    	mSendButton.setOnClickListener(new OnClickListener() {
//    	    @Override
//    	    public void onClick(View v) {
//    		//sendMessage();
//    	    	final String inputContent = mInputField.getText().toString();
//    	    }
//    	});
	}
  
    
	private void setParams() {
		//设置SelectPicPopupWindow的View
        this.setContentView(mMenuView);
        //设置SelectPicPopupWindow弹出窗体的宽
        this.setWidth(LayoutParams.FILL_PARENT);
        //设置SelectPicPopupWindow弹出窗体的高
        this.setHeight(LayoutParams.WRAP_CONTENT);
        //设置SelectPicPopupWindow弹出窗体可点�?
        this.setFocusable(true);
        //设置SelectPicPopupWindow弹出窗体动画效果
        this.setAnimationStyle(R.style.Popup_Animation_UpDown);
        //实例化一个ColorDrawable颜色为半透明
        //ColorDrawable dw = new ColorDrawable(0xb0000000);
        ColorDrawable dw = new ColorDrawable(0x00000000);
        //设置SelectPicPopupWindow弹出窗体的背�?
        this.setBackgroundDrawable(dw);
        //mMenuView添加OnTouchListener监听判断获取触屏位置如果在�?择框外面则销毁弹出框
        mMenuView.setOnTouchListener(new OnTouchListener() {
             
            public boolean onTouch(View v, MotionEvent event) {
                 
                int height = mMenuView.findViewById(R.id.pop_layout).getTop();
                int y=(int) event.getY();
                if(event.getAction()==MotionEvent.ACTION_UP){
                    if(y<height){
                        dismiss();
                    }
                }               
                return true;
            }
        });
	}
 
	private List<Integer> ids;
	private Map<Integer, String> names;
	
public class ExpressionItemAdapter extends BaseAdapter {
    	
    	Context c;
    	public ExpressionItemAdapter(Context c) {
			// TODO Auto-generated constructor stub
    		this.c = c;
    		//mInflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		@Override
		public int getCount() {
			return ids.size();
		}

		@Override
		public Object getItem(int position) {
			return ids.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ImageView iv_common_expression_grid_item_image;
			if (convertView == null) {
				convertView = View.inflate(c,
						R.layout.message_emote_item, null);
				iv_common_expression_grid_item_image = (ImageView) convertView
						.findViewById(R.id.emote_imageview);
				convertView.setTag(iv_common_expression_grid_item_image);
			} else {
				iv_common_expression_grid_item_image = (ImageView) convertView
						.getTag();
			}
			iv_common_expression_grid_item_image
					.setImageResource((Integer) getItem(position));
			return convertView;
		}

	}

	
	private void loadExpression(String regularExpression) {
		ids = new ArrayList<Integer>();
		names = new HashMap<Integer, String>();
		Class<drawable> drawable = R.drawable.class;
		Field[] fields = drawable.getDeclaredFields();
		for (Field field : fields) {
			String name = field.getName();
			if (field.getName().matches(regularExpression)) {
				try {
					int id = field.getInt(null);
					ids.add(id);
					names.put(id, name);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	private void insertIntoEditText(SpannableString expression) {
		int index = mInputField.getSelectionStart();
		Editable text = mInputField.getText();
		if (index >= 0 && index < text.length()) {
			text.insert(index, expression);
		} else {
			text.append(expression);
		}
	}
	
	private void choseEmoteTosend(AdapterView<?> adpater, int location) {
		int resId = (Integer) adpater
				.getItemAtPosition(location);
		ImageSpan is = new ImageSpan(adpater.getContext(), resId);
		String value = names.get(resId);
		SpannableString ss = new SpannableString(value);
		ss.setSpan(is, 0, value.length(),
				SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
		insertIntoEditText(ss);
	}
	
}